package com.servlet;

import com.bean.Book;
import com.dao.BooksUtilsDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;


@WebServlet("/RemoveServlet")
public class RemoveServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int removeid = Integer.parseInt(request.getParameter("id"));
        HttpSession session = request.getSession();
        BooksUtilsDao dao = new BooksUtilsDao();

        @SuppressWarnings("unchecked")
		ArrayList<Book> cart = (ArrayList<Book>) session.getAttribute("cart");
        for (int i=0;i<cart.size();i++) {
            int id = Integer.parseInt(cart.get(i).getId());
            if (id == removeid) {
                try {
                    dao.remove(request.getParameter("id"));
                    cart.remove(i);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        response.sendRedirect("CartServlet");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
